package com.fqgj.xjd.user.exception;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * name:异常处理
 * auth:ting.li@yuntu-inc.com
 * date:2017/9/18下午2:53
 * version: v1.0.0
 **/
@Aspect
@Component
public class UserExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserExceptionHandler.class);
    @Pointcut("execution(* com.fqgj.xjd.user.service.impl.*.*(..))")
    private void externalPointCut(){}

    @Around("externalPointCut()")
    public Object readAround(ProceedingJoinPoint point) throws Throwable{
        Object result = null;
        try {
            long startTime = System.nanoTime();
            result = point.proceed(point.getArgs());
            long endTime = System.nanoTime();
            long cost = (endTime-startTime)/1000000;
            StringBuffer buffer = new StringBuffer(point.getTarget().getClass()+"."+point.getSignature().getName() +
                            " method excute args:" + JSON.toJSONString(point.getArgs()) +",result:" +
                            JSON.toJSONString(result));
            if(cost>200){
                buffer.append(",cost over 200") ;
            }
            buffer.append("real cost:" + cost);
//            LOGGER.info(buffer.toString());
        } catch (Exception e) {
            LOGGER.error(point.getTarget().getClass()+"."+point.getSignature().getName()+
                    " method excute error,args:" + JSON.toJSONString(point.getArgs()) +
                    ",result:" + JSON.toJSONString(result),e);

            if(e.getCause() instanceof SQLException){
                LOGGER.error("执行数据库操作出现异常,请求参数:{}"," service:"+point.getTarget().getClass()+
                        "."+point.getSignature().getName()+":"+JSON.toJSONString(point.getArgs()), e);
            }
            return e;
        }
        return result;
    }
}
